package com.example.administrator.foodrowfresh.views;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.example.administrator.foodrowfresh.R;
import com.example.administrator.foodrowfresh.adapter.FlashSaleAdapter;
import com.example.administrator.foodrowfresh.classfile.JsonParserHomePage;
import com.example.administrator.foodrowfresh.configs.HomepageConfig;
import com.example.administrator.foodrowfresh.models.TimeLimit;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class FlashSale extends AppCompatActivity implements PullToRefreshBase.OnRefreshListener{

    private PullToRefreshListView refreshListView;
    private List<TimeLimit.DataBean.FlashSaleBean> flashSaleBeans;
    private FlashSaleAdapter saleAdapter;
    private Callback.Cancelable cancelable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash_sale);
        initView();
    }
    public void initView()
    {
        refreshListView= (PullToRefreshListView) findViewById(R.id.pulltolistviewflashsale_id);
        flashSaleBeans=new ArrayList<>();
        //绑定适配器
        saleAdapter=new FlashSaleAdapter(flashSaleBeans,this);
        refreshListView.setAdapter(saleAdapter);

        downloadText(HomepageConfig.TIMELIMIT_PATH);
    }

    public void onBack(View view) {
        finish();
    }
    /**
     * 限时抢购
     */
    public void downloadText(String PATH)
    {
        RequestParams params=new RequestParams(PATH);
        cancelable = x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    List<TimeLimit.DataBean.FlashSaleBean> list = JsonParserHomePage.parserJsonTimeLimit(result);
                    flashSaleBeans.addAll(list);
                    saleAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelable.cancel();
    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        downloadText(HomepageConfig.TIMELIMIT_PATH);
        refreshListView.onRefreshComplete();
    }
}
